using System;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using QFramework;
using Newtonsoft.Json.Linq;

[System.Serializable]
public class LiveDataAckItem
{
    public string msg_id;
    public string msg_type;
    public long client_time;
}

[System.Serializable]
public class LiveDataAckData
{
    public long room_id;
    public int ack_type;
    public List<LiveDataAckItem> data;
}

[System.Serializable]
public class LiveDataAckMessage
{
    public string cmd = "liveDataAck";
    public LiveDataAckData data;
    public long timestamp;
    public long msg_id;
}

public class UpLoadLogs : MonoBehaviour
{
    private static UpLoadLogs instance;
    public static UpLoadLogs Instance
    {
        get
        {
            if (instance == null)
            {
                var go = new GameObject("UpLoadLogs");
                instance = go.AddComponent<UpLoadLogs>();
                DontDestroyOnLoad(go);
            }
            return instance;
        }
    }

    private Queue<LiveDataAckItem> ackQueue = new Queue<LiveDataAckItem>();
    private const int MAX_QUEUE_SIZE = 100; // 最大队列大小
    private const float SEND_INTERVAL = 1f; // 发送间隔（秒）
    private float lastSendTime;

    // Start is called before the first frame update
    void Start()
    {
        // 注册事件监听
        StringEventSystem.Global.Register(EventID.SocketMessageReceived, (object[] args) => OnSocketMessageReceived(args));
    }


    private void OnSocketMessageReceived(object[] args)
    {
        if (args.Length < 2) return;

        string msgType = args[0] as string;
        string msgId = args[1] as string;

        if (string.IsNullOrEmpty(msgType) || string.IsNullOrEmpty(msgId)) return;

        // 创建确认项
        var ackItem = new LiveDataAckItem
        {
            msg_id = msgId,
            msg_type = msgType,
            client_time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
        };

        // 添加到队列
        lock (ackQueue)
        {
            if (ackQueue.Count >= MAX_QUEUE_SIZE)
            {
                ackQueue.Dequeue(); // 如果队列满了，移除最旧的消息
            }
            ackQueue.Enqueue(ackItem);
        }
    }

    // Update is called once per frame
    void Update()
    {
        // 定期发送确认消息
        if (Time.time - lastSendTime >= SEND_INTERVAL)
        {
            SendAckMessages();
            lastSendTime = Time.time;
        }
    }

    private async void SendAckMessages()
    {
        List<LiveDataAckItem> itemsToSend;
        lock (ackQueue)
        {
            if (ackQueue.Count == 0) return;
            
            itemsToSend = new List<LiveDataAckItem>(ackQueue);
            ackQueue.Clear();
        }

        try
        {
            var ackMessage = new LiveDataAckMessage
            {
                data = new LiveDataAckData
                {
                    room_id = Convert.ToInt64(GlobalData.RoomId),
                    ack_type = 1,
                    data = itemsToSend
                },
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                msg_id = DateTime.Now.Ticks
            };

            string json = JsonConvert.SerializeObject(ackMessage);
            await WebSocketManager.Instance.SendMessageAsync(json);
            Debug.Log($"发送消息确认: {json}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"发送消息确认失败: {ex.Message}");
            // 发送失败时，将消息重新加入队列
            lock (ackQueue)
            {
                foreach (var item in itemsToSend)
                {
                    ackQueue.Enqueue(item);
                }
            }
        }
    }

    void OnDestroy()
    {
        StringEventSystem.Global.UnRegister(EventID.SocketMessageReceived, (object[] args) => OnSocketMessageReceived(args));
    }
}
